package net.jjjshop.common.service.lbt.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import net.jjjshop.common.constants.ConfConstants;
import net.jjjshop.common.entity.lbt.JybBusinessOrderEntity;
import net.jjjshop.common.entity.lbt.JybTradeOrderEntity;
import net.jjjshop.common.entity.lbt.LbUserWalletEntity;
import net.jjjshop.common.entity.lbt.TradeOrderEntityRequest;
import net.jjjshop.common.mapper.lbt.JybTradeOrderMapper;
import net.jjjshop.common.service.lbt.JybBusinessOrderService;
import net.jjjshop.common.service.lbt.JybTradeOrderService;
import net.jjjshop.common.service.lbt.LbUserWalletService;
import net.jjjshop.common.service.lbt.UserBillService;
import net.jjjshop.common.service.user.UserService;
import net.jjjshop.common.util.BigDecimalUtil;
import net.jjjshop.framework.util.LoginUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;


/**
 * 交易订单表 接口实现类
 */

@Service("jybTradeOrderService")
public class JybTradeOrderServiceImpl extends ServiceImpl<JybTradeOrderMapper, JybTradeOrderEntity> implements JybTradeOrderService {
    @Autowired
    private JybTradeOrderMapper dao;
    @Autowired
    private UserService userService;
    @Autowired
    private JybBusinessOrderService jybBusinessOrderService;
    @Autowired
    private LbUserWalletService walletService;
    @Autowired
    private UserBillService userBillService;
    /**
     * JybTradeOrder列表查询
     * @param
     * @return
     */
    @Override
    public IPage<JybTradeOrderEntity> getList(Integer uid, Integer tType, Integer status, Integer classType,Integer page, Integer limit) {


        Integer UserId = LoginUtil.getUserId();
        Page<JybTradeOrderEntity> pages = new Page<>(page,limit);
//        LambdaQueryWrapper<JybTradeOrderEntity> lqw = Wrappers.lambdaQuery();
//        lqw.eq(JybTradeOrderEntity::getUid, UserId);
//        lqw.orderByDesc(JybTradeOrderEntity::getCreateTime);
        if (tType == 1){
            return dao.selectOrder(pages,UserId,null,status,classType);
        }else
        {
            return dao.selectOrder(pages,null,UserId,status,classType);
        }
    }

    @Override
    public JybTradeOrderEntity queryOrderInfo(String orderNo) {
        return dao.queryOrderInfo(LoginUtil.getUserId(),orderNo);
    }

    @Override
    public List<JybTradeOrderEntity> userHandleOrder() {
        return dao.userHandleOrder(LoginUtil.getUserId());
    }

    @Override
    public IPage<JybTradeOrderEntity> selectOrder(Integer uid, Integer tType, Integer status, Integer classType, Integer page, Integer limit) {
        Page<JybTradeOrderEntity> pages = new Page<>(page,limit);
            return dao.selectOrder(pages,null,null,status,classType);
    }


    //后台取消订单
    public Boolean cancelOrder(TradeOrderEntityRequest request){
        JybTradeOrderEntity findTradeOrder = getById(request.getId());
        JybBusinessOrderEntity businessOrder = jybBusinessOrderService.getById(findTradeOrder.getGid());
        if (null == findTradeOrder || businessOrder == null){
            throw new RuntimeException("没有找到交易订单");
        }
        if (findTradeOrder.getStatus() == 3){
            throw new RuntimeException("订单已取消过了");
        }
        if (findTradeOrder.getStatus() == 4){
            throw new RuntimeException("订单已超时");
        }

        Integer duty = request.getDuty(); //1卖家责任，2买家责任，3双方无责
        Boolean cancelOrder = handCancelOrder(findTradeOrder, businessOrder, duty);
        if (cancelOrder) {
            return true;
        }else{
            return false;
        }
    }

    public Boolean handCancelOrder(JybTradeOrderEntity findTradeOrder,JybBusinessOrderEntity businessOrder,Integer duty){
        if (businessOrder.getType() == 1){
            findTradeOrder.setStatus(3);
            findTradeOrder.setRemarks("管理处理订单");
            updateById(findTradeOrder);
            if (duty == 1){
                Integer uid = findTradeOrder.getBuyerId();
                LbUserWalletEntity walletInfo = walletService.getUserWalletInfo(uid);
                if (null == walletInfo || null == walletInfo.getId()) {
                    throw new RuntimeException("没有找到钱包");
                }
                if (businessOrder.getClassType() == 0){
                    BigDecimal allPrice = findTradeOrder.getNum();
                    walletInfo.setScore(BigDecimalUtil.addDouble(walletInfo.getScore(), allPrice));
                    if(! userBillService.addBillRecord("管理处理订单权益卡到账", ConfConstants.INTEGRAL_TYPE,1,allPrice,uid,null)){
                        throw new RuntimeException("取消异常，联系客服");
                    }
                }else if (businessOrder.getClassType() == 1){
                    walletInfo.setMoney(BigDecimalUtil.addDouble(walletInfo.getMoney(), findTradeOrder.getNum()));
                    if(! userBillService.addBillRecord("管理处理订单贡献值到账",ConfConstants.COMMISSION_TYPE,1,findTradeOrder.getNum(),uid,null)){
                        throw new RuntimeException("取消异常，联系客服");
                    }
                }

                if (!walletService.updateById(walletInfo)) {
                    throw new RuntimeException("操作取消异常，联系客服");
                }
                return true;
            }
            if (duty == 2){
                businessOrder.setStatus(0);
                businessOrder.setNum(BigDecimalUtil.addDouble(businessOrder.getNum(), findTradeOrder.getNum()));
                if (jybBusinessOrderService.updateById(businessOrder)){
                    return true;
                }else{
                    return false;
                }
            }
        }
        if (businessOrder.getType() == 2){
            findTradeOrder.setStatus(3);
            findTradeOrder.setRemarks("管理处理订单");
            updateById(findTradeOrder);
            if (duty == 1){
                businessOrder.setStatus(0);
                businessOrder.setNum(BigDecimalUtil.addDouble(businessOrder.getNum(), findTradeOrder.getNum()));
                if (jybBusinessOrderService.updateById(businessOrder)){
                    return true;
                }else{
                    return false;
                }
            }
            if (duty == 2){
                Integer uid = findTradeOrder.getSellerId();
                LbUserWalletEntity walletInfo = walletService.getUserWalletInfo(uid);
                if (null == walletInfo || null == walletInfo.getId()) {
                    throw new RuntimeException("没有找到钱包");
                }
                if (businessOrder.getClassType() == 0){
                    BigDecimal allPrice = findTradeOrder.getNum();
                    walletInfo.setScore(BigDecimalUtil.addDouble(walletInfo.getScore(), allPrice));
                    if(! userBillService.addBillRecord("管理处理订单权益卡到账",ConfConstants.INTEGRAL_TYPE,1,allPrice,uid,null)){
                        throw new RuntimeException("取消异常，联系客服");
                    }
                }else if (businessOrder.getClassType() == 1){
                    walletInfo.setMoney(BigDecimalUtil.addDouble(walletInfo.getMoney(), findTradeOrder.getNum()));
                    if(! userBillService.addBillRecord("管理处理订单贡献值到账",ConfConstants.COMMISSION_TYPE,1,findTradeOrder.getNum(),uid,null)){
                        throw new RuntimeException("取消异常，联系客服");
                    }
                }
                if (!walletService.updateById(walletInfo)) {
                    throw new RuntimeException("操作取消异常，联系客服");
                }
                return true;
            }
        }
        return true;
    }


}
